<template>
    <div class="container container-achievementDeliver">
        <AchievementTop :showBtn="false" :detailInfo="detailInfo" />
        <div class="page-panell">
            <div class="panel-title">
                <div class="panel-content">我的方案</div>
            </div>
        </div>
        <a-spin tip="Loading..." :spinning="formLoading">
            <a-form-model layout="inline" class="yuan-form panel-content">
                <div class="form-panel">
                    <a-form-model-item class="yuan-form-row" label="是否从已有需求方案导入" :label-col="{ style: { width: '170px' } }"
                        :wrapper-col="{ style: { width: 'calc(100% - 170px)' } }">
                        <a-radio-group v-model="pageType" @change="pageTypeChange">
                            <a-radio :value="1">否</a-radio>
                            <a-radio :value="2">
                                <span>是</span>
                                <span v-if="pageType===2">: </span>
                                <a-select style="width:200px" class="yuan-form-input" v-model="selectMyAchId" placeholder="请选择方案"
                                    v-if="pageType===2" @change="selectMyAch">

                                    <a-select-option :value="item.id"
                                        v-for="item in myAchList" :key="item.id">{{item.demandName}}</a-select-option>
                                </a-select>

                            </a-radio>

                        </a-radio-group>
                    </a-form-model-item>
                </div>
            </a-form-model>
            <a-form-model layout="inline" class="yuan-form panel-content" :label-col="{ style: { width: '160px' } }"
                :wrapper-col="{ style: { width: 'calc(100% - 160px)' } }" ref="form" :model="formData" :rules="rules">
                <div class="form-panel">
                    <a-form-model-item label="封面图" class="yuan-form-item" v-if="pageReady">
                        <UploadVue :uploadLength="1" @uploadChange="uploadChangeCoverImageUrl"
                            :defImgList="formData.coverImageUrl?[formData.coverImageUrl]:[]" />
                        <div style="line-height:30px">jpg.png.gif格式.不超过2MB</div>
                    </a-form-model-item>

                    <a-form-model-item class="yuan-form-item yuan-form-col3" label="需求名称" prop="demandName">
                        <a-input class="yuan-form-input" v-model="formData.demandName" placeholder="请输入"></a-input>
                    </a-form-model-item>
                    <a-form-model-item class="yuan-form-row" label="技术需求描述" prop="technicalDescription">
                        <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                            v-model="formData.technicalDescription" placeholder="请输入描述" :maxLength="1000" />
                    </a-form-model-item>

                    <a-form-model-item class="yuan-form-row" label="分类" prop="category">
                        <a-radio-group v-model="formData.category">
                            <a-radio value="生产研发需求">生产研发需求</a-radio>
                            <a-radio value="技术服务需求">技术服务需求</a-radio>
                            <a-radio value="临床效果需求">临床效果需求</a-radio>
                            <a-radio value="生产技术需求">生产技术需求</a-radio>
                            <a-radio value="其他">其他需求</a-radio>
                            <!-- <a-radio value="其他">
                                <span>其他：</span>
                                <CountInputVue style="margin-left:5px" class="yuan-form-input" v-model="formData.categoryOther"
                                    :maxNum="15" placeholder="请输入" />
                            </a-radio> -->
                        </a-radio-group>
                    </a-form-model-item>
                    <a-form-model-item class="yuan-form-row" label="细分领域" prop="subCategory">
                        <a-checkbox-group v-model="formData.subCategory">
                            <a-checkbox :value="item.content" v-for="item in territoryList"
                                :key="item.id">{{item.content}}</a-checkbox>
                        </a-checkbox-group>
                    </a-form-model-item>

                    <a-form-model-item class="yuan-form-row" label="拟投入金额" prop="investmentMin">
                        <a-input class="yuan-form-input" v-model="formData.investmentMin" placeholder="请输入"></a-input>
                        <span>~</span>
                        <a-input class="yuan-form-input" v-model="formData.investmentMax" placeholder="请输入"></a-input>
                        <span> 万元</span>
                    </a-form-model-item>
                    <a-form-model-item class="yuan-form-row" label="企业/单位名称" prop="companyName">
                        <a-input class="yuan-form-input" v-model="formData.companyName" placeholder="请输入"></a-input>
                    </a-form-model-item>
                    <a-form-model-item class="yuan-form-row" label="联系人" prop="contacts">
                        <a-input class="yuan-form-input" v-model="formData.contacts" placeholder="请输入"></a-input>
                    </a-form-model-item>
                    <a-form-model-item class="yuan-form-row" label="联系方式" prop="contactInfo">
                        <a-input class="yuan-form-input" v-model="formData.contactInfo" placeholder="请输入"></a-input>
                    </a-form-model-item>
                    <a-form-model-item class="yuan-form-item yuan-form-col5" label="需求截止时间" prop="deadline">
                        <a-date-picker class="yuan-form-input" placeholder="需求截止时间" v-model="formData.deadline" inputReadOnly
                            valueFormat="YYYY-MM-DD" @change="deadlineChange" />
                        <span v-show="formData.deadline"> 
                             剩余天数：{{formData.residueDay>=0?formData.residueDay+'天':'已过期'}}
                        </span>
                    </a-form-model-item>
                    <a-form-model-item class="yuan-form-row" label="需求发布地址" prop="placeAreaCode">
                        <a-cascader class="yuan-form-input" :options="addrData" v-model="formData.placeAreaCode" placeholder="请选择"
                            @change="onAddrChange" />
                    </a-form-model-item>
                    <a-form-model-item class="yuan-form-row" label="授权经纪人">
                        <span v-show="formData.technicalRepresentative">{{formData.technicalRepresentative}} </span>
                        <a-button type="primary" @click="()=>userVisible=true">选择技术经纪人</a-button>
                    </a-form-model-item>

                </div>
                <div class="bottom-btn-box">
                    <a-button class="bottom-btn" type="primary" @click="save">提交方案</a-button>
                </div>
            </a-form-model>
        </a-spin>
        <a-modal title="提示" :visible="visible" :confirm-loading="formLoading" @ok="onOk" @cancel="closeModal" okText="确定"
            cancelText="取消">
            <div>
                您的方案需要递交到平台进行审核，在平台审核通过会自动投递到该需求，您可以在工作台-成果管理查看投递进度。
            </div>
            <div>
                是否投递该方案？
            </div>
        </a-modal>

        <UserVue :visible="userVisible" @closeModal="() => userVisible = false" @sureClose="selectUser" />
    </div>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import AchievementTop from "./components/achievementTop.vue";
import CountInputVue from "@/components/countInput.vue";
import areaJson, { getAreaWords } from "@/utils/area";
import UserVue from "../../components/addUserModal.vue";
import api from "@/api/api";
import { getStorageUserInfo } from "@/utils";
import UploadVue from "@/components/upload.vue";
import { UserModule } from "@/store/modules/userModules";
@Component({
    name: "dom",
    components: { AchievementTop, CountInputVue, UserVue, UploadVue },
})
export default class index extends Vue {
    visible = false;
    formLoading = false;
    pageType = 1;
    formData: any = {};
    pageReady = false;
    rules = {
        demandName: [{ required: true, message: "请输入需求名称", trigger: "change" }],
        technicalDescription: [{ required: true, message: "请输入描述", trigger: "change" }],
        category: [{ required: true, message: "请选择分类", trigger: "change" }],
        subCategory: [{ required: true, message: "请选择细分领域", trigger: "change" }],
        investmentMin: [{ required: true, message: "请填写投入金额", trigger: "change" }],
        companyName: [{ required: true, message: "请填写企业单位名称", trigger: "change" }],
        contacts: [{ required: true, message: "请填写联系人", trigger: "change" }],
        contactInfo: [{ required: true, message: "请填写联系方式", trigger: "change" }],
        deadline: [{ required: true, message: "请选择截至时间", trigger: "change" }],
        placeAreaCode: [{ required: true, message: "请选择发布地址", trigger: "change" }],
        hasTechnicalRepresentative: [{ required: true, message: "请选择技术经纪人", trigger: "change" }],
    };
    jumpDeliver() {
        this.$router.push({ name: "demandDeliver" });
    }
    closeModal() {
        this.visible = false;
    }
    save() {
        if (!this.formData.coverPicture) {
            this.$message.error("请上传封面图");
            return;
        }
        // if (!this.formData.demandType) {
        //     this.$message.error("请选择成果类型");
        //     return;
        // }
        if (this.formData.hasTechnicalRepresentative === 1 && !this.formData.technicalRepresentative) {
            this.$message.error("请选择技术经纪人");
            return;
        }
        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (!valid) return;
            this.visible = true;
        });
    }
    onOk() {
        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (!valid) return;
            this.formLoading = true;
            try {
                let data;
                if (this.pageType === 1) {
                    // 如果不是导入
                    data = {
                        achievementId: this.detailInfo.id,
                        ...this.formData,
                        hasTechnicalRepresentative: this.formData.technicalRepresentative ? 1 : 0,
                        ifDeliver: 1,
                        //achievementDifferentiate: this.formData.demandType,
                    };
                } else {
                    data = {
                        achievementId: this.detailInfo.id,
                        ifDeliver: 0,
                        ...this.formData,
                    };
                }

                const res = await api.addDemand(data);
                this.$message.success("保存成功,您可以在工作台查看对接进度");
                this.formData = {};
                this.pageReady = false;
                this.$nextTick(() => {
                    this.pageReady = true;
                });
                this.closeModal();
            } finally {
                this.formLoading = false;
            }
        });
    }
    mounted() {
        this.pageReady = true;
        this.setAddrData();
        const query = this.$route.query;
        this.pageId = query.id ? query.id + "" : "";

        const userInfo = getStorageUserInfo();
        if (!userInfo || !userInfo.token) {
            UserModule.setShowLoginPanel(true)
            this.$message.warning("登录失效");
            this.$router.go(-1);
            return;
        }
        this.formLoading = true;
        Promise.all([this.getTerritoryList(), this.getDetail(), this.getMyAch()]).then(() => {
            //
            this.formLoading = false;
        });
    }

    pageId = "";
    detailInfo: any = {};
    async getDetail() {
        try {
            const res = await api.getActList({
                id: this.pageId,
            });
            this.detailInfo = res.data;
        } finally {
            // this.loading = false;
        }
    }

    territoryList = [];
    async getTerritoryList() {
        try {
            const res = await api.getSetting("3");
            this.territoryList = res.data;
        } finally {
            //
        }
    }

    userVisible = false;
    selectUser(userInfo) {
        this.formData.technicalRepresentative = userInfo.name;
        this.formData.technicalPhone = userInfo.phone;
    }
    myAchList: any[] = [];
    async getMyAch() {
        try {
            const res = await api.getMyDemand();
            this.myAchList = res.data;
        } finally {
            //
        }
    }
    selectMyAchId = "";
    selectMyAch() {
        this.pageReady = false;
        const find = this.myAchList.find((item) => item.id === this.selectMyAchId);
        if (find) {
            // find.applicationIndustry = find.applicationIndustry ? JSON.parse(find.applicationIndustry) : [];
            // find.belongToTechnologyCategory = find.belongToTechnologyCategory ? JSON.parse(find.belongToTechnologyCategory) : [];
            // find.embodyForm = find.embodyForm ? JSON.parse(find.embodyForm) : [];
            // find.promotionForm = find.promotionForm ? JSON.parse(find.promotionForm) : [];
            if (find.subCategory) {
                find.subCategory = typeof find.subCategory === "string" ? JSON.parse(find.subCategory) : find.subCategory;
            }

            find.placeAreaCode = find.code.split(",");
        }
        this.formData = { ...find };
        this.$nextTick(() => {
            this.pageReady = true;
        });
    }

    pageTypeChange() {
        this.pageReady = false;
        this.formData = {};
        this.selectMyAchId = "";
        this.$nextTick(() => {
            this.pageReady = true;
        });
    }

    uploadChangeCoverImageUrl(e) {
        this.formData.coverPicture = e.length ? e[0].url : "";
    }

    addrData: any[] = [];
    setAddrData() {
        this.addrData = areaJson;
    }
    onAddrChange(e: any) {
        this.formData.code = e.join(",");
        this.formData.location = getAreaWords(e);
    }

    deadlineChange() {
        if (!this.formData.deadline) return "";
        const nowTime = new Date().getTime();
        const deadlineTime = new Date(this.formData.deadline.replace(/-/g, "/")).getTime();
        const day = (deadlineTime - nowTime) / (24 * 60 * 60 * 1000);
        this.formData.deadlineDay = Math.ceil(day);
    }
}
</script>

<style lang="scss">
.container-achievementDeliver {
    .panel-content {
        width: 1350px;
        margin: 0 auto;
    }
    .panel-title {
        font-weight: bold;
        font-size: 22px;
        color: #2f65f3;
        background-color: #fff;

        .panel-content {
            height: 40px;
            display: flex;
            align-items: center;
        }
        .panel-content::before {
            content: "";
            display: inline-block;
            height: 26px;
            width: 1px;
            border-right: 3px solid #2f65f3;
            margin-right: 20px;
        }
    }
    .yuan-form {
        background-color: #fff;
        margin-top: 15px;
        padding: 20px;
    }
    .bottom-btn-box {
        text-align: center;
        padding: 50px;
    }
    .bottom-btn {
        height: 40px;
        width: 120px;
        font-size: 14px;
    }
}
</style>
